package com.jiuzhe.commercial.ui.house;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.HouseStayListBean;
import com.jiuzhe.commercial.bean.ossTokenBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.main.MainActivity;
import com.jiuzhe.commercial.utils.RxBus;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by huanghao on 2018/4/27.
 */

public class AddPhotoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, BGASortableNinePhotoLayout.Delegate {

    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_PHOTO_PREVIEW = 2;
    @BindView(R.id.snpl_moment_add_photos)
    BGASortableNinePhotoLayout mPhotosSnpl;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    private List<String> facilityIdList;
    private List<String> imgList = new ArrayList<>();
    private Dialog alertDialog;
    private String token;
    private String id;
    private List<String> mImgUrls;
    private HouseStayListBean houseStayListBean;
    private boolean flag = true;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.add_photo_activity);
        setTitle("添加照片");
        flag = true;
        houseStayListBean = (HouseStayListBean) getIntent().getSerializableExtra("room");
        if(null != houseStayListBean)
        mImgUrls = houseStayListBean.getImgs();
        if (mImgUrls!=null && mImgUrls.size()>0)
        mPhotosSnpl.addMoreData((ArrayList<String>) mImgUrls);
        imgList.clear();
        // 设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this);
    }

    @OnClick({R.id.bt_submit})
    public void onclick(View v) {
        switch (v.getId()) {
            case R.id.bt_submit:
                if (UIUtils.isFastClick()) {
                    if (mPhotosSnpl != null && mPhotosSnpl.getData().size() > 0) {
                        dialog.show();
                        submitImgToOss();
                    } else {
                        UIUtils.showToastSafe("请先添加图片");
                    }
                }
                break;
        }
    }

    /**
     * 图片先提交到阿里云
     */
    private void submitImgToOss() {
        int totalNum = 0;
        List<String> data = mPhotosSnpl.getData();
        for (String datum : data) {
            if (!datum.startsWith("https://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/")){
                ossToken(revitionImageSize(datum));
            }else {
                flag = false;
                imgList.add(datum);
            }
        }
        if (imgList != null){
            for (String s : imgList) {
                if (s.startsWith("https://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/")){
                    totalNum += 1;
                }
            }
        }

        if (totalNum == mPhotosSnpl.getData().size()) {
            flag = false;
            submit();
        }
    }


    /**
     * 上传图片到服务器
     */
    private void submit() {
        String skuid = getIntent().getStringExtra("skuid");
        String token = SPUtil.getString(AddPhotoActivity.this, Constants.TOKEN);
        String id = SPUtil.getString(this, Constants.ID);
        HashMap<String, Object> map = new HashMap<>();
        if (null == houseStayListBean ){
            map.put("skuId", skuid);
        }else {
            map.put("skuId", Constants.HOUSESTAYLISTBEAN.getId());
        }

        map.put("imgUrlList", imgList);
        String addStr = Constants.ADD_ROOM2.substring(Constants.ADD_ROOM2.lastIndexOf("0/")+1) + "?token=";
        String signStrg = UIUtils.Md5(addStr + token);
        String url = Constants.ADD_ROOM2 + "?token=" + id + "&&sign=" + signStrg;

        HttpClient.post2(this, url, map, new CallBack<String>() {
            @Override
            public void onSuccess(String code) {
              //  UIUtils.showToastSafe("");
                RxBus.getInstance().post(houseStayListBean);
                Constants.HOUSESTAYLISTBEAN = null;
                imgList.clear();
                dialog.dismiss();
                show();
            }

            @Override
            public void onFailure(int errorType, String message) {
                super.onFailure(errorType, message);
                dialog.dismiss();
                imgList.clear();
            }
        });
    }

    private void show() {
        alertDialog = new Dialog(this, R.style.EasyListDialogStyle);
        mView = LayoutInflater.from(this).inflate(R.layout.dialog_photo_hint, null);
        alertDialog.setContentView(mView);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        window.setAttributes(lp);
        Button btOk = alertDialog.findViewById(R.id.bt_ok);
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (flag) {
                    Intent intent = new Intent(AddPhotoActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else {
                    finish();
                }
            }
        });
    }

    /**
     * 上传图片  阿里云
     *
     * @param
     */
    private void ossToken(final String path) {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "123");
        token = SPUtil.getString(AddPhotoActivity.this, Constants.TOKEN);
        id = SPUtil.getString(this, Constants.ID);
        String autoSignStr = Constants.OSS_TOKEN.substring(Constants.OSS_TOKEN.lastIndexOf("0/")+1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        String url = Constants.OSS_TOKEN + "?token=" + id + "&&sign=" + signStr;
        HttpClient.get(this, url, map, new CallBack<ossTokenBean>() {
            @Override
            public void onSuccess(ossTokenBean result) {
                upload(path, result.getAccessKeyId(), result.getAccessKeySecret(), result.getSecurityToken());
            }
        });
    }


    @Override
    protected void loadData() {

    }

    /**
     * 选择图片
     */
    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "jiuzhe");

            Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                    .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                    .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                    .selectedPhotos(null) // 当前已选中的图片路径集合
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));

        } else if (requestCode == RC_PHOTO_PREVIEW) {
            mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        if (mPhotosSnpl.getData().size()>1){
            mPhotosSnpl.removeItem(position);
            mImgUrls.remove(position);
        }else {
            UIUtils.showToastSafe("请至少保留一张图片在提交");
        }
    }


    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }


    private void deletePhotoItem(final int position) {
        HashMap<String, Object> map = new HashMap<>();
        String token = SPUtil.getString(AddPhotoActivity.this, Constants.TOKEN);
        String id = SPUtil.getString(AddPhotoActivity.this, Constants.ID);
        String autoSignStr = Constants.IMGDELETE.substring(Constants.IMGDELETE.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("skuId", Constants.HOUSESTAYLISTBEAN.getId());
        map.put("img",mImgUrls.get(position));

        String url = Constants.IMGDELETE + "?token=" + id + "&sign=" + signStr;
        HttpClient.post2(this, url, map, new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
                UIUtils.showToastSafe("删除照片成功");
                RxBus.getInstance().post(houseStayListBean);
                mPhotosSnpl.removeItem(position);
            }
        });
    }

    /**
     * 压缩
     *
     * @param path
     * @return
     */
    public String revitionImageSize(String path) {
        //System.out.println("path = " + path);
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            in.close();

            int i = 0;
            // options.inJustDecodeBounds=true那么将不返回实际的bitmap对象，不给其分配内存空间但是可以得到一些解码边界信息即图片大小等信息
            // outHeight(图片原始高度)和 outWidth(图片的原始宽度)
            // inSampleSize表示缩略图大小为原始图片大小的几分之一
            // options.outWidth >> i(右移运算符)表示：outWidth/(2^i)
            while (true) {
                if ((options.outWidth >> i <= 500)
                        && (options.outHeight >> i <= 500)) {
                    in = new BufferedInputStream(
                            new FileInputStream(new File(path)));
                    options.inSampleSize = (int) Math.pow(2.0D, i); // 幂运算 i为几次方
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    break;
                }
                i += 1;
            }
            String newPath = Constants.APP_FOLD + path.substring(path.lastIndexOf("/"));
            saveBitmapToFile(bitmap, newPath);
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param _file
     * @throws IOException
     */
    public void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 上传图片到阿里云
     *
     * @param path
     * @param accessKeyId
     * @param accessKeySecret
     * @param securityToken
     */
    private void upload(String path, String accessKeyId, String accessKeySecret, String securityToken) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 在移动端建议使用STS方式初始化OSSClient。
// 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
//该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("jzt-hotel-img", imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                imgList.add("https://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/" + imgName + ".jpg");
                if (imgList.size() == mPhotosSnpl.getData().size())
                    submit();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog != null) {
            alertDialog = null;
        }
    }
}